<?php


class ChangePasswordForm extends BaseForm {

    public function configure() {
        sfProjectConfiguration::getActive()->loadHelpers('I18N');

        $this->setWidgets(array(
            'old_password' => new sfWidgetFormInputPassword(array('label' => __('Old Password'),
	                                                                           'type' => 'password'),
	                                                                    array('class' => 'input_box')),
            
            'new_password' => new sfWidgetFormInputPassword(array('label' => __('New Password'),
	                                                                           'type' => 'password'),
	                                                                    array('class' => 'input_box')),

            're_password' => new sfWidgetFormInputPassword(array('label' => __('Confirm Password'),
	                                                                           'type' => 'password'),
	                                                                    array('class' => 'input_box')),
        ));

        $this->setValidators(array(
            'old_password' => new sfValidatorString(),
            'new_password' => new sfValidatorString(array(
                'max_length' => 18,
                'min_length' => 3
                )),
            're_password'  => new sfValidatorString(array(
                'max_length' => 18,
                'min_length' => 3
                )),
        ));

        $this->validatorSchema->setPostValidator(new sfValidatorAnd(array(
            new sfValidatorSchemaCompare('new_password', '==', 're_password', array(), array('invalid' => 'The new passwords must match')),
            new sfValidatorCallback(
                    array(
                        'callback'=> array($this, 'checkpassword')
                    ),
                    array('invalid'  => 'Old Password wrong!')
                )
        )));

        $this->widgetSchema->setNameFormat('changepassword[%s]');
    }

    public function checkpassword(sfValidatorCallback $validator, $values) {
        if(!$this->getUser()->checkPassword($values['old_password'])){
            throw new sfValidatorError($validator, 'invalid');
        }else {
            return $values;
        }
    }

    protected function getTable() {
        return Doctrine::getTable('sfGuardUser');
    }

    protected function getUser() {
        return sfContext::getInstance()->getUser();
    }
    
    public function save() {
        $this->getUser()->setPassword($this->getValue('new_password'));
    }
}
